package com.sh.data.engine.domain.dataquality.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sh.data.engine.domain.dataquality.service.DataQualityScheduleService;
import com.sh.data.engine.domain.dataquality.service.DataQualityService;
import com.sh.data.engine.job.core.context.XxlJobHelper;
import com.sh.data.engine.job.core.handler.annotation.XxlJob;
import com.sh.data.engine.repository.dao.dataquality.entity.DataQualityScheduleEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author tinglan.ys
 * @description:
 * @date 2022/2/24 下午5:36
 */
@Component
@Slf4j
public class DataQualityTask {

    @Autowired
    private DataQualityService dataQualityService;

    @Autowired
    private DataQualityScheduleService dataQualityScheduleService;

    /**
     * @description : 敏捷版新代码
     * @author : tinglan.ys
     * @date : 2022/2/30
     */
    @XxlJob(value = "DataQualityTask")
    public void run() {

        final long jobId = XxlJobHelper.getJobId();
        String jobIdStr = String.valueOf(jobId);

        DataQualityScheduleEntity dataQualitySchedule =
            dataQualityScheduleService.getOne(
                new LambdaQueryWrapper<DataQualityScheduleEntity>()
                    .eq(DataQualityScheduleEntity::getXxlJobId, jobIdStr)
                    .eq(DataQualityScheduleEntity::getStatus, 0));

        if (null == dataQualitySchedule) {
            return;
        }

        Long projectId = dataQualitySchedule.getProjectId();
        Long tblId = dataQualitySchedule.getTblId();

        final Integer cycleDependence = dataQualitySchedule.getCycleDependence();
        if (Objects.equals(1, cycleDependence)) {
            // 判断上一周期是否结束
            final Integer lastJobStatus = dataQualityService.getLastJobStatus(projectId, tblId);
            if (Objects.equals(lastJobStatus, 0)) {
                return;
            }
        }

        log.info("表id为 " + tblId + " 空间id为" + projectId + "的数据质量任务开始.......");

        // 开始执行
        dataQualityService.processDataQuality(
            projectId, tblId, null, dataQualitySchedule.getCycle(), null);
    }
}
